package com.keyroy.game.puzzle_rpg.models.render;

import java.awt.Rectangle;

import com.keyroy.game.puzzle_rpg.models.interfaces.SWTDrawable;
import com.keyroy.game.puzzle_rpg.models.puzzle.PuzzleMap;
import com.keyroy.game.puzzle_rpg.models.puzzle.PuzzleSet;
import com.keyroy.game.puzzle_rpg.models.puzzle.Tile;

public class PuzzleMapRender extends SWTDrawable {
	private Rectangle buff;
	private Object color = getColor(0xee82ee);
	private Object white = getColor(0xffffff);
	private PuzzleMap puzzleMap;
	private PuzzleSet puzzleSet;
	private boolean drawGrid = true;
	private boolean drawLocation;

	public PuzzleMapRender(PuzzleMap puzzleMap) {
		this.puzzleMap = puzzleMap;
		init();
	}

	private final void init() {
		if (puzzleMap != null) {
			buff = new Rectangle();
			puzzleSet = puzzleMap.getPuzzleSet();
			buff.width = puzzleSet.gridWidth;
			buff.height = puzzleSet.gridHeight;
		}
	}

	@Override
	public void onDraw() {
		if (puzzleMap != null) {
			setAlpha(255);
			if (drawGrid) {
				// ee82ee
				setColor(color);
			}
			for (int y = 0; y < puzzleSet.rows; y++) {
				for (int x = 0; x < puzzleSet.columns; x++) {
					Tile tile = puzzleMap.tiles[x][y];
					if (tile != null) {
						setAlpha(tile.alpha);
						int tx = tile.getCx();
						int ty = tile.getCy();
						if (tile.tileType.getImage() == null) {
							tile.tileType.setImage(getImage(tile));
						}

						drawImage(tile.tileType.getImage(), tx, ty);

						if (drawLocation) {
							drawString(x + "" + y, tx, ty);
						}

						if (drawGrid) {
							setColor(white);
							buff.x = tx;
							buff.y = ty;
							drawRect(buff.x, buff.y, buff.width, buff.height);
						}
					}
				}
			}
		}
	}

	public void setDrawGrid(boolean drawGrid) {
		this.drawGrid = drawGrid;
	}

	public void setDrawLocation(boolean drawLocation) {
		this.drawLocation = drawLocation;
	}

	private final Object getImage(Tile tile) {
		if (tile.tileType.icon == null) {
			return getColorImage(tile.tileType.color, puzzleSet.gridWidth, puzzleSet.gridHeight);
		} else {
			return getImage(tile.tileType.icon, puzzleMap.getPuzzleSet().gridWidth, puzzleMap.getPuzzleSet().gridHeight);
		}
	}

}
